﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace testProtobuf.Network
{
    class NetworkController
    {
        const int RECEIVEBUFFER_SIZE = 1024;

        NetworkStream _receiveStream = null;
        MemoryStream _sendStream = null;
        TcpConnection _tcpConnection = null;
        byte[] _recvTempBytes = null;
        public void Create()
        {
            _recvTempBytes = new byte[RECEIVEBUFFER_SIZE];
            _receiveStream = new NetworkStream();
            _sendStream = new MemoryStream();
            _tcpConnection = new TcpConnection();

            _tcpConnection.Create("127.0.0.1", 8888, RECEIVEBUFFER_SIZE, false);
            _receiveStream.Create(RECEIVEBUFFER_SIZE);
        }

        public void Destory()
        {
            if (_tcpConnection != null)
                _tcpConnection.Destroy();

            if (_receiveStream != null)
                _receiveStream.Destroy();

            _recvTempBytes = null;
        }

        public void SendMessage(int head, int length ,ref byte[] message)
        {
            int sendBufferSize = length + Common.HEAD_SIZE;
            if (sendBufferSize > RECEIVEBUFFER_SIZE)
            {
                Console.WriteLine("NetworkStream Buffer Overflow !");
                return;
            }
            BinaryWriter binaryWriter = new BinaryWriter(_sendStream);
            binaryWriter.Seek(0, 0);
            binaryWriter.Write(sendBufferSize);
            binaryWriter.Write(head);
            binaryWriter.Write(message);

            _tcpConnection.SendMessage(_sendStream.GetBuffer(), (int)_sendStream.Length);
        }

        public void Update(float frame_time)
        {
            ReceiveMessage();
        }

        void ReceiveMessage()
        {
            if (_receiveStream != null && _tcpConnection != null)
            {
                int length = _tcpConnection.ReceiveMessage(ref _recvTempBytes, _receiveStream.GetLeftBufferLength());
                if (length > 0)
                {
                    _receiveStream.Append(_recvTempBytes, length);

                    RemoveFirstMessage();
                }

            }
        }

        void RemoveFirstMessage()
        {
            _receiveStream.SeekTo(0);
            NetworkHead head = new NetworkHead();
            bool flag = StreamHelper.ReadHead(ref _receiveStream, ref head);
            if (!flag)
                Console.WriteLine("NetorkController RemoveMessageFailed !!");

            _receiveStream.EraseData(0, head._packageLength);
        }


    }
}
